

<template>
  <van-field
    :value="code"
    @input="change"
    :name="name"
    label="验证码"
    placeholder="验证码"
    :rules="[
      { required: true, message: '请填写验证码' },
      { pattern: reg.code, message: '请输入正确的验证码' },
    ]"
    center
    clearable
    left-icon="apps-o"
  >
    <template #button>
      <van-button
        native-type="button"
        v-if="flag"
        size="small"
        type="primary"
        :disabled="!reg.phone.test(phone)"
        @click="startSendCode"
        >发送验证码</van-button
      >
      <van-button
        native-type="button"
        v-else
        size="small"
        type="default"
        disabled
      >
        <van-count-down :time="total * 1000" @finish="onfinish">
          <template #default="timeData">
            <span class="block"
              >剩余 {{ timeData.minutes * 60 + timeData.seconds }} S</span
            >
          </template>
        </van-count-down>
      </van-button>
    </template>
  </van-field>
</template>


<script>
import { checkPhoneApi, todoSentCode } from "@/api/api";

export default {
  data() {
    return {
      flag: true,
      total: 180,
    };
  },
  model: {
    prop: "code",
    event: "changecode",
  },
  props: {
    name: {
      type: String,
      default: "captcha",
    },
    code: String,
    phone: String,
  },
  methods: {
    change(val) {
      this.$emit("changecode", val);
    },
    onfinish() {
      this.flag = true;
      this.total = 180;
    },
    async startSendCode() {
      let res = await checkPhoneApi({
        phone: this.phone,
      });
      if (res.result) {
        // 已经注册 可以登录
        let res = await todoSentCode({
          phone: this.phone,
        }).catch((err) => {
          this.ShowToast("验证码发送失败 ");
        });
        if (res.code == 200 && res.data) {
          this.flag = false;
          this.ShowSuccess("验证码发送成功");
        } else {
        }
      } else {
        this.ShowToast("请先注册手机号");
      }
    },
  },
};
</script>
